package com.leon.lifeenginespace.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @description: bean后处理器
 * @author: WT
 * @date: 2024/4/28 21:46
 * @Version 1.0
 **/
@Slf4j
@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {

    private static final String NAME = "lifeCycleBean";

    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        if (NAME.equals(beanName)) {
            log.info("<<<<销毁之前执行，postProcessBeforeDestruction");
        }
    }

    /**
     * bean 实例化之前
     *
     * @param beanClass
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (NAME.equals(beanName)) {
            log.info("<<<<实例化之前执行，postProcessBeforeInstantiation 把原来bean替换掉");
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (NAME.equals(beanName)) {
            log.info("<<<<实例化之后执行，postProcessAfterInstantiation 如果返回false 跳过依赖注入阶段");
        }
        return true;
    }


    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if (NAME.equals(beanName)) {
            log.info("<<<<依赖注入阶段执行，postProcessProperties @Autowired @value @Resource");
        }
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (NAME.equals(beanName)) {
            log.info("<<<<初始化之前执行，postProcessBeforeInitialization 这返回的对象会替换掉原来的bean @PostConstruct @ConfigurationProperties");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (NAME.equals(beanName)) {
            log.info("<<<<初始化之后执行，postProcessAfterInitialization");
        }
        return bean;
    }
}